package com.tgy.leetcode;

import java.util.Arrays;

/**
 * @Author: tgy
 * @Date: 12/1/20 10:20 AM
 *
 * https://leetcode-cn.com/problems/sliding-window-maximum/
 */
public class _239_滑动窗口最大值_02 {

    public int[] maxSlidingWindow(int[] nums, int k) {

        if (nums == null || k <= 0 || nums.length < k) {

            return new int[0];
        }

        if (k == 1) {

            return nums;
        }


        int[] leftToRight = new int[nums.length];
        int[] rightToLeft = new int[nums.length];

        rightToLeft[nums.length - 1] = nums[nums.length - 1];
        for (int i = 0; i < nums.length; i++) {

            if (i % k == 0) {

                leftToRight[i] = nums[i];
            }else {

                leftToRight[i] = Math.max(nums[i],leftToRight[i - 1]);
            }

            if (i != 0) {

                int ri = nums.length - 1 - i;

                if (ri % k == (k - 1)) {

                    rightToLeft[ri] = nums[ri];
                }else {
                    rightToLeft[ri] = Math.max(nums[ri],rightToLeft[ri + 1]);
                }
            }
        }


        int len = nums.length - k + 1;
        int[] ret = new int[len];

        for (int i = 0; i < len ; i++) {

            int right = i + k - 1;

            if (right % k == k - 1) {

                ret[i] = leftToRight[right];
            }else {

                ret[i] = Math.max(rightToLeft[i],leftToRight[right]);
            }
        }

        return ret;
    }


}
